package com.example.wanandroid.controller;

import com.example.wanandroid.pojo.Coin;
import com.example.wanandroid.pojo.LoginToken;
import com.example.wanandroid.pojo.User;
import com.example.wanandroid.result.Result;
import com.example.wanandroid.result.ResultUtil;
import com.example.wanandroid.service.TokenService;
import com.example.wanandroid.service.UserService;
import com.example.wanandroid.util.CookieUtils;
import com.example.wanandroid.util.TextUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    TokenService tokenService;


    /**
     * 注册
     *
     * @param username
     * @param password
     * @param repassword
     * @return
     */
    @ResponseBody
    @PostMapping("/register")
    public Result register(String username, String password, String repassword) {
        if (TextUtils.isEmpty(username)) {
            return ResultUtil.error(-1, "用户名不能为空");
        }
        if (TextUtils.isEmpty(password) || password.length() < 6) {
            return ResultUtil.error(-1, "密码长度必须大于6位！");
        }
        User user = userService.selectUserByUsername(username);
        if (user != null) {
            return ResultUtil.error(-1, "用户名已经被注册！");
        }
        user = new User();
        user.setUsername(username);
        user.setNickname(username);
        user.setPassword(password);
        user.setAdmin(false);
        user.setPublicName(username);
        int retCode = userService.insert(user);

        user = userService.selectByPrimaryKey(user.getId());
        return ResultUtil.success("注册成功！", user);
    }

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @ResponseBody
    @PostMapping("/login")
    public Result login(String username, String password, HttpServletResponse response) {
        //查询用户是否存在
        User user = userService.selectUserByUsername(username);
        if (user == null) {
            return ResultUtil.error(-1, "账号未注册！");
        }
        // -1 errorMsg=账号密码不匹配！
        if (!user.getPassword().equals(password)) {
            return ResultUtil.error(-1, "账号密码不匹配");
        }

        //把用户信息插入到表中，返回用户信息，有用户的id,根据id，采用addLoginTicket方法生成token

        String token = addLoginToken(user.getId());
        user.setToken(token);

        //写入cookie
        //loginUserName=daqiang; Expires=Sat, 16-May-2020 13:07:26 GMT; Path=/
        //token_pass=5d9b90bcb70640183e09d1e755ead823; Expires=Sat, 16-May-2020 13:07:26 GMT; Path=/
        //loginUserName_wanandroid_com=daqiang; Domain=wanandroid.com; Expires=Sat, 16-May-2020 13:07:26 GMT; Path=/
        //token_pass_wanandroid_com=5d9b90bcb70640183e09d1e755ead823; Domain=wanandroid.com; Expires=Sat, 16-May-2020 13:07:26 GMT; Path=/
        CookieUtils.writeCookie(response, "loginUserName", username);
        CookieUtils.writeCookie(response, "token_pass", token);
        return ResultUtil.success("登录成功！", user);
    }


    //生成插入token
    private String addLoginToken(long userId) {
        LoginToken loginTicket = new LoginToken();
        loginTicket.setUserId(userId);
        Date date = new Date();
        //token失效时间  30小时
        date.setTime(date.getTime() + 1000 * 3600 * 30);
        loginTicket.setExpiredDate(date);
        loginTicket.setToken(UUID.randomUUID().toString().replaceAll("-", ""));
        tokenService.insert(loginTicket);
        return loginTicket.getToken();
    }


    /**
     * 退出登录
     *
     * @param response
     * @return
     */
    @GetMapping("/logout/json")
    public Result logout(HttpServletResponse response) {
        CookieUtils.writeCookie(response, "loginUserName", "");
        CookieUtils.writeCookie(response, "token_pass", "");
        return ResultUtil.success();
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    @GetMapping(value = "/getUsers")
    public Result getUsers(Integer page, Integer pageSize) {
        if (page == null) page = 1;
        if (pageSize == null) pageSize = 20;
        PageInfo<HashMap<String, Object>> pageInfo = userService.getUsers(page, pageSize);

        return ResultUtil.success(pageInfo);
    }

    @GetMapping("/userinfo/json")
    public Result userInfoJson(HttpServletRequest request){
        User user = (User) request.getAttribute("user");
        Coin coin = new Coin();
        coin.setUserId(user.getId());
        coin.setCoinCount(100);
        coin.setLevel(2);
        coin.setRank(5429);
        coin.setUsername(user.getUsername());
        return ResultUtil.success(coin);

    }

}
